# coding=utf-8
"""
    @project: wlou
    
    @file： application_serializers.py
    @date：2023/11/7 10:02
    @desc:
"""
import hashlib
import uuid
from django.core import cache, validators

from rest_framework import serializers
from django.db.models import QuerySet
from common.exception.app_exception import AppApiException
from common.util.field_message import ErrMessage
from django.utils.translation import gettext_lazy as _

from xpack.models import SystemApiKey

chat_cache = cache.caches['chat_cache']

class SystemParamsSerializer(serializers.Serializer):
    

    class SystemApiKeySerializerModel(serializers.ModelSerializer):
        class Meta:
            model = SystemApiKey
            fields = "__all__"

    class SystemApiKeySerializer(serializers.Serializer):
        user_id = serializers.UUIDField(required=True, error_messages=ErrMessage.uuid(_("User ID")))
        def is_valid(self, *, raise_exception=False):
            super().is_valid(raise_exception=True)

        def generate(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            secret_key = 'system-' + hashlib.md5(str(uuid.uuid1()).encode()).hexdigest()
            system_api_key = SystemApiKey(id=uuid.uuid1(), secret_key=secret_key, user_id=self.data.get("user_id"))
            system_api_key.save()
            return SystemParamsSerializer.SystemApiKeySerializerModel(system_api_key).data

        def list(self, with_valid=True):
            if with_valid:
                self.is_valid(raise_exception=True)
            return [SystemParamsSerializer.SystemApiKeySerializerModel(system_api_key).data for
                    system_api_key in
                    QuerySet(SystemApiKey).filter()]

        class Edit(serializers.Serializer):
            is_active = serializers.BooleanField(required=False, error_messages=ErrMessage.boolean(_("Availability")))

            allow_cross_domain = serializers.BooleanField(required=False,
                                                          error_messages=ErrMessage.boolean(
                                                              _("Is cross-domain allowed")))

            cross_domain_list = serializers.ListSerializer(required=False,
                                                           child=serializers.CharField(required=True,
                                                                                       error_messages=ErrMessage.char(
                                                                                           _("Cross-domain address"))),
                                                           error_messages=ErrMessage.char(_("Cross-domain list")))

        class Operate(serializers.Serializer):

            api_key_id = serializers.CharField(required=True, error_messages=ErrMessage.char(_("ApiKeyid")))

            def delete(self, with_valid=True):
                if with_valid:
                    self.is_valid(raise_exception=True)
                api_key_id = self.data.get("api_key_id")
                system_api_key = QuerySet(SystemApiKey).filter(id=api_key_id).first()
                system_api_key.delete()

            def edit(self, instance, with_valid=True):
                if with_valid:
                    self.is_valid(raise_exception=True)
                api_key_id = self.data.get("api_key_id")
                system_api_key = QuerySet(SystemApiKey).filter(id=api_key_id).first()
                if system_api_key is None:
                    raise AppApiException(500, _('APIKey does not exist'))
                if 'is_active' in instance and instance.get('is_active') is not None:
                    system_api_key.is_active = instance.get('is_active')
                if 'allow_cross_domain' in instance and instance.get('allow_cross_domain') is not None:
                    system_api_key.allow_cross_domain = instance.get('allow_cross_domain')
                if 'cross_domain_list' in instance and instance.get('cross_domain_list') is not None:
                    system_api_key.cross_domain_list = instance.get('cross_domain_list')
                system_api_key.save()
